package com.mk.task;

import com.mk.entity.Chat;
import com.mk.mapper.ChatMapper;
import com.mk.service.ChatRedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * 定时将Redis中的聊天信息存入MySQL
 */
@Component
@RequiredArgsConstructor
public class ChatHistoryTask {

    private final ChatRedisService chatRedisService;
    private final ChatMapper chatMapper;


    @Scheduled(cron = "${task.chatHistoryScheduled.cron}") // 每 5 分钟执行一次
    public void saveChatHistoryToMySQL() {
        List<Object> messages = chatRedisService.fetchAndClearMessages();
        if (messages != null && !messages.isEmpty()) {
            List<Chat> chatMessages = messages.stream()
                .map(obj -> (Chat) obj)
                .toList();
            chatMapper.insert(chatMessages);
            chatRedisService.clearMessages();
        }
    }
}
